package cn.com.dashihui.web.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.com.dashihui.kit.QrCodeUtil;
import cn.com.dashihui.web.dao.AdminSeller;
import cn.com.dashihui.web.dao.User;

public class AdminService {
	
	public boolean findExistsByUsername(String username){
		return AdminSeller.me().findFirst("SELECT * FROM t_auth_admin_seller WHERE username=?",username)!=null;
	}
	/**
	 * 根据Phonenumber
	 * @param username
	 * @return
	 */
	public boolean findExistsByPhonenumber(String phonenumber){
		return User.me().findFirst("SELECT * FROM t_bus_user WHERE phone=?",phonenumber)!=null;
	}
	
/*	public boolean addUser(AdminSeller newObject){
		return newObject.save();
	}*/
	
	public boolean delUser(final int id){
		//事务处理，同时删除用户记录，并删除相应的用户角色关联记录
		return Db.tx(new IAtom(){
			@Override
			public boolean run() throws SQLException {
				boolean ret1 = AdminSeller.me().deleteById(id);
				Db.update("DELETE FROM t_auth_admin_roles_seller WHERE userid=?",id);
				return ret1;
			}
		});
	}
	/**
	 * 
	 * @param userid
	 * @return
	 */
	public int findRoleIdByUserid(int userid){
		return Db.queryInt("SELECT roleid FROM t_auth_admin_roles_seller WHERE userid=?",userid);
	}
	/**
	 * 
	 * @param userid
	 * @return
	 */
	public Record findByUserid(int userid){
		return Db.findFirst("SELECT  * FROM  t_bus_seller WHERE userid=? ",userid);
	}
	
	
	public boolean editUser(AdminSeller object){
		return object.update();
	}
	
	@Before(Tx.class)
	public boolean editMinePwd(AdminSeller currentUser,String passwordOld,String passwordNew) throws Exception{
		AdminSeller user = AdminSeller.me().findById(currentUser.getInt("id"));
		if(user==null){
			return false;
		}
		PasswordService svc = new DefaultPasswordService();
		if(!svc.passwordsMatch(passwordOld, user.getStr("password"))){
			throw new Exception("原密码输入不正确");
		}else{
			return user.set("password", svc.encryptPassword(passwordNew)).update();
		}
	}
	
	public AdminSeller findEnabledByUsername(String username){
		return AdminSeller.me().findFirst("SELECT * FROM t_auth_admin_seller WHERE username=? AND enabled=1",username);
	}
	/**
	 * 根据userid,获取角色
	 * @param userid
	 * @return
	 */
	public int findByRoleId(int userid){
		return Db.queryInt("SELECT C.id  from t_auth_admin_seller as A inner JOIN  t_auth_admin_roles_seller as B ON A.id=B.userid  INNER JOIN t_auth_roles_seller AS C ON B.roleid = C.id where userid=?" ,userid);
	}
	/**
	 * 根据userid,获取所属分公司的id
	 * @param userid
	 * @return
	 */
	public String findByStoreid(int userid){
		return Db.queryStr("SELECT  storeid FROM t_auth_admin_seller where id= ?" ,userid);
	}
	/**
	 * 根据userid,获取所属公司的sellerId
	 * @param userid
	 * @return
	 */
	public String findBysellerId(int userid){
		return Db.queryStr("SELECT D.sellerId FROM t_auth_admin_seller as A INNER JOIN t_bus_seller as D ON A.id=D.userid  where A.id=  ?" ,userid);
	}
   
	/**
	 * 分公司Id查所属公司
	 * @param storeid
	 * @return
	 */
	public Record findBysellerId(String storeid){
		return Db.findFirst("select sellerId from t_dict_store where storeid = ?",storeid);
	}
	
	public AdminSeller findByIdAdmin(int id){
		return AdminSeller.me().findFirst("SELECT A.*,ifnull(A.contribution,0) as contribution  FROM t_auth_admin_seller A  where A.id=?",id);
	}
	
	public AdminSeller findById(int id){
		return AdminSeller.me().findFirst("SELECT A.*,ifnull(A.contribution,0) as contribution ,"
				+ " C.id as RoleId,C.name as aname,E.sellerId, "
				+ "D.title FROM t_auth_admin_seller as A "
				+ "inner JOIN  t_auth_admin_roles_seller as B ON A.id=B.userid "
				+ "INNER JOIN t_auth_roles_seller C ON B.roleid = C.id "
				+ "INNER JOIN t_dict_store as D ON A.storeid=D.storeid "
				+ "INNER JOIN t_bus_seller as E ON D.sellerId=E.sellerId  "
				+ "where 1=1 and A.id=?",id);
	}
	public AdminSeller findByIds(int id){
		return AdminSeller.me().findFirst("select * from t_auth_admin_seller where id=?",id);
	}
	public Page<Record> findByPage(int pageNum, int pageSize,int RoleId,String storeid,String sellerId,String tel,String name,String sellers,String stores,String jobs){
		StringBuffer sqlExcept=null;
		String head=null;
		if(RoleId==1){
			sqlExcept = new StringBuffer("FROM t_auth_admin_seller as A inner JOIN  t_auth_admin_roles_seller as B ON A.id=B.userid INNER JOIN t_auth_roles_seller C ON B.roleid = C.id left JOIN t_dict_store as D ON A.storeid=D.storeid  where 1=1"); 
			head=" SELECT  A.*,C.name as aname,C.id as RoleId ,D.title";
		}else{
			sqlExcept = new StringBuffer("FROM t_auth_admin_seller as A inner JOIN  t_auth_admin_roles_seller as B ON A.id=B.userid INNER JOIN t_auth_roles_seller C ON B.roleid = C.id INNER JOIN t_dict_store as D ON A.storeid=D.storeid  where 1=1"); 
			head=" SELECT  A.*,C.id as RoleId,C.name as aname,D.sellerId,D.title";
		}
		 
		List<Object> params = new ArrayList<Object>();
		if(RoleId==2){
	    sqlExcept.append(" and C.id!=1 and D.sellerId=?");  
	    params.add(sellerId);
		}
		if(RoleId==3){
		    sqlExcept.append(" and C.id=4 and A.storeid=?");
		    params.add(storeid);
			}
		if(!StrKit.isBlank(tel)){
    		sqlExcept.append(" AND A.phonenumber =?");
    		params.add(tel);
		}
	    if(!StrKit.isBlank(name)){
	    	sqlExcept.append(" AND A.trueName =?");
	    	params.add(name);
		}

	    //公司查询
	    if(!StrKit.isBlank(sellers)){
	    	sqlExcept.append(" AND D.sellerId in ('"+sellers+"')");
	    }
	  //分公司查询
	    if(!StrKit.isBlank(stores)){
	    	sqlExcept.append(" AND D.storeid in ('"+stores+"')");
		}
	  //职位查询
	    if(!StrKit.isBlank(jobs)){
	    	sqlExcept.append(" AND C.id in ('"+jobs+"')");
		}	  
		sqlExcept.append(" ORDER BY A.createDate DESC");
		return Db.paginate(pageNum, pageSize, head, sqlExcept.toString(),params.toArray());
	}

	public AdminSeller findByUsername(String username){
		return AdminSeller.me().findFirst("SELECT * FROM t_auth_admin_seller WHERE username=? and enabled=1 ",username);
	}
	
	public List<Record> findRolesByUser(int userid){
		return Db.find("SELECT * FROM v_admin_roles WHERE userid=?",userid);
	}
	
	/**
	 * 新添加的用户是公司角色
	 */
	public int findRoles(int userid){
		
		return Db.update("INSERT INTO t_auth_admin_roles_seller(userid,roleid) VALUES( ?,'2')", userid);
	}
	/**
	 * 新添加的用户是店员角色
	 */
   public int findRolesSe(int userid){
		
		return Db.update("INSERT INTO t_auth_admin_roles_seller(userid,roleid) VALUES( ?,'4')", userid);
	}/**
	 * 新添加的用户是联系人角色
	 */
   public int findRolesDj(int userid){
	
	return Db.update("INSERT INTO t_auth_admin_roles_seller(userid,roleid) VALUES( ?,'3')", userid);
   }

	public int findadminByid(String username){
		return Db.queryInt("SELECT id as userid FROM t_auth_admin_seller where username =?", username);
	}
	
	
	
	/**
	 * 获得当前用户登录的角色权限
	 * @param userid
	 * @return
	 */
   public int getRoles(int userid){	
	   
		return Db.queryInt("SELECT  B.roleid from t_auth_admin_seller as A "
				+ "inner JOIN  t_auth_admin_roles_seller as B ON A.id=B.userid  "
				+ "where A.id =?", userid);
        }
   /**
    * 
    * @param userid
    * @return
    */
   public Record findSelleridByUserId(int userid){
		return Db.findFirst("SELECT D.sellerId,A.VipPower FROM t_auth_admin_seller as A INNER JOIN t_bus_seller as D ON A.id=D.userid  where A.id= ?",userid);
	}
   /***
    * 
    * @param userid
    * @return
    */
   public Record findstoreidByUserId(int userid){
		return Db.findFirst("SELECT B.sellerId,B.id,B.storeid,B.title,A.VipPower,A.id as Adid FROM t_auth_admin_seller as A  INNER JOIN t_dict_store as B ON A.storeid=B.storeid  where A.id= ?",userid);
	}

   public boolean getPost(int id) {
	   String qrcodePath = null;
	   Map<String, Object> qrcodeMap = new HashMap<String, Object>();
				try {
					qrcodeMap =QrCodeUtil.getPost(id);
					qrcodePath = (String) qrcodeMap.get("qrcodePath");
					boolean bn=saveQrcaode(id,qrcodePath);
					if(bn){
						return true;
					}else{
						return false;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false;
	}
	public boolean saveQrcaode(int id,String qrcodePath){
		AdminSeller admin=findByIds(id);
		admin.set("QrCode", qrcodePath);
		return admin.update();
	}
	/*修改销售姓名*/
	public void setDaogou(String trueName,String oldName){
		Db.update("Update t_bus_user set toBossOneId=? where toBossOneId=?",trueName,oldName);
	}
	/**
	* 根据电话号码获取用户对象,验证当前用户是否存在
	* @param phone
	* @return
	*/
	public User findUserByPhone(String phonenumber){
		return User.me().findFirst("SELECT name from t_bus_user where phone=?", phonenumber);
	}
	/**
	* 根据电话号码获取用户对象,验证当前用户是否存在
	* @param phone
	* @return
	*/
	public int findSeidBySellerId(String sellerId){
		return Db.queryInt("SELECT id from t_bus_seller where sellerId=?", sellerId);
	}
}
